/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.openapi.WaybillRouteService;
import org.jeecg.modules.third.tosapi.constant.enums.GoodsCargoTypeEnum;
import org.jeecg.modules.third.tosapi.dto.TosApiBaseResDTO;
import org.jeecg.modules.third.tosapi.dto.resp.WaybillResultResponseBo;
import org.jeecg.modules.third.tosapi.dto.shippingnote.*;
import org.jeecg.modules.third.tosapi.service.TosApiService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerCompany;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerCompanyService;
import org.jeecg.modules.wlhy.customer.service.impl.HyCustomerServiceImpl;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.impl.HyDriverServiceImpl;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.impl.HyVehicleServiceImpl;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.impl.HyOrderServiceImpl;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.PointDataListVO;
import org.jeecg.modules.wlhy.shipping.entity.WaybillRouteVO;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 快货运平台
 *
 * @author duanlikao
 * @created 2022/3/23
 */
@Service
public class ShippingNoteTosApiService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ShippingNoteEtcService.class);

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private HyOrderServiceImpl orderService;

    @Autowired
    private HyCustomerServiceImpl customerService;

    @Autowired
    private HyDriverServiceImpl driverService;

    @Autowired
    private HyVehicleServiceImpl vehicleService;

    /**
     * 申报企业信息
     */
    @Autowired
    private IHyCompanyService companyService;

    /**
     * 珠海快货运
     */
    @Autowired
    private TosApiService tosApiService;

    /**
     * 快货运申报托运人合同信息
     */
    @Autowired
    private IHyCustomerCompanyService customerCompanyService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Autowired
    private WaybillRouteService waybillRouteService;
    /**
     * 快货运创建运单
     *
     * @param hyShippingNote
     * @return
     */

    public TosApiBaseResDTO waybillCreate(HyShippingNote hyShippingNote) {

        HyShippingNote hyShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (hyShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据!");
        }

        if (!hyShippingNoteDb.getTosIdentification().equals("1")) {
            throw new JeecgBootException("该运单不属于快货运运单!");
        }

        HyOrder hyOrder = orderService.getById(hyShippingNoteDb.getOrderId());
        if (hyOrder == null) {
            throw new JeecgBootException("该运单货源信息不存在!");
        }

        HyVehicle hyVehicle = vehicleService.getById(hyShippingNoteDb.getVehicleId());
        if (hyVehicle == null) {
            throw new JeecgBootException("该运单车辆信息不存在!");
        }
        HyDriver hyDriver = driverService.getById(hyShippingNoteDb.getDriverId());
        if (hyDriver == null) {
            throw new JeecgBootException("该运单司机信息不存在!");
        }

        HyCompany company = companyService.getById(hyShippingNoteDb.getCompanyId());
        if (company == null) {
            throw new JeecgBootException("该运单分公司信息不存在!");
        }

        HyCustomer hyCustomer = customerService.getById(hyShippingNoteDb.getCustomerId());
        if (hyCustomer == null) {
            throw new JeecgBootException("该运单货主信息不存在!");
        }

        CreateShippingNoteDTO createShippingNoteDTO = getCreateShippingNoteDTO(hyShippingNoteDb, hyOrder, hyVehicle,
                hyDriver, company, hyCustomer);
        return tosApiService.waybillCreate(createShippingNoteDTO);
    }

    /**
     * 快货运-组装运单信息
     *
     * @param hyShippingNote
     * @param hyOrder
     * @param hyVehicle
     * @param hyDriver
     * @param company
     * @param hyCustomer
     * @return
     */
    private CreateShippingNoteDTO getCreateShippingNoteDTO(HyShippingNote hyShippingNote, HyOrder hyOrder,
            HyVehicle hyVehicle, HyDriver hyDriver, HyCompany company, HyCustomer hyCustomer) {
        CreateShippingNoteDTO createShippingNoteDTO = new CreateShippingNoteDTO();

        createShippingNoteDTO.setSource_no(hyOrder.getOrderNum());
        createShippingNoteDTO.setWaybill_no(hyShippingNote.getShippingNoteNumber());
        createShippingNoteDTO.setTransport_org_type("ROAD_TRANSPORT");
        createShippingNoteDTO.setBusiness_mode("PROPRIETARY_TRADING");
        createShippingNoteDTO.setTransport_org("TRADITIONAL_TRANSPORTATION");
        createShippingNoteDTO.setVehicle_count(1);
        createShippingNoteDTO.setWaybill_upload_time(
                new Date().getTime()
        );

        createShippingNoteDTO.setCarrier(company.getCompanyName());
        createShippingNoteDTO.setCarrier_identity(company.getCreditCode());

        createShippingNoteDTO.setWaybill_create_time(
                hyShippingNote.getCreateTime().getTime()
        );
        createShippingNoteDTO.setBusiness_type("TRUNK_GENERAL_CARGO_TRANSPORTATION");
        createShippingNoteDTO.setSend_time(
                hyShippingNote.getStatusDtLoading() != null ? hyShippingNote.getStatusDtLoading().getTime() : new Date().getTime()

        );
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, 7);// 把日期往后增加7天.整数往后推,负数往前移动
        Date newtime = calendar.getTime();
        createShippingNoteDTO.setReceive_time(
                hyShippingNote.getStatusDtSign() != null ? hyShippingNote.getStatusDtSign().getTime() : newtime.getTime()
        );

        createShippingNoteDTO.setLoad_address(hyShippingNote.getSendAddress());
        createShippingNoteDTO.setLoad_district(hyShippingNote.getSendAreaCode());
        createShippingNoteDTO.setConsignor_identity(
                hyCustomer.getCustomerType().equals("2") ? hyCustomer.getCreditCode() : hyCustomer.getIdcard());
        createShippingNoteDTO.setSender_name(hyShippingNote.getSendContactName());
        createShippingNoteDTO.setSender_phone(hyShippingNote.getSendContactTel());
        createShippingNoteDTO.setSender_no(
                hyCustomer.getCustomerType().equals("2") ? hyCustomer.getCreditCode() : hyCustomer.getIdcard());

        createShippingNoteDTO.setReceiver_name(hyShippingNote.getReceiveContactName());
        createShippingNoteDTO.setReceiver_phone(hyShippingNote.getReceiveContactTel());
        createShippingNoteDTO.setReceiver_no(
                hyCustomer.getCustomerType().equals("2") ? hyCustomer.getCreditCode() : hyCustomer.getIdcard());
        createShippingNoteDTO.setReceive_address(hyShippingNote.getReceiveAddress());
        createShippingNoteDTO.setReceive_district(hyShippingNote.getReceiveAreaCode());

        BigDecimal num = new BigDecimal("100");
        int fee = 0;
        if (hyShippingNote.getDriverFee() != null) {
            fee = hyShippingNote.getDriverFee().multiply(num).setScale(0, BigDecimal.ROUND_DOWN).intValue();
        }
        createShippingNoteDTO.setCustomer_ship_fee(fee);
        createShippingNoteDTO.setDriver_ship_fee(fee);
        createShippingNoteDTO.setInclude_tax("TAX_INCLUDED_AMOUNT");

        List <SubWayBillDTO> subWayBillList = getSubWayBillList(hyShippingNote, hyOrder, hyCustomer, hyDriver, hyVehicle);
        createShippingNoteDTO.setSub_way_bill_list(subWayBillList);

        createShippingNoteDTO.setRemark("运单结算后更新运费");
        return createShippingNoteDTO;
    }

    /**
     * 快货运-组装子运单信息
     *
     * @param hyShippingNote
     * @param hyOrder
     * @param hyCustomer
     * @param hyDriver
     * @param hyVehicle
     * @return
     */
    private List<SubWayBillDTO> getSubWayBillList(HyShippingNote hyShippingNote, HyOrder hyOrder,
            HyCustomer hyCustomer, HyDriver hyDriver, HyVehicle hyVehicle) {

        List<SubWayBillDTO> subWayBillDTOS = new ArrayList<>();
        SubWayBillDTO subWayBillDTO = new SubWayBillDTO();
        subWayBillDTO.setSub_waybill_no("0000");
        subWayBillDTO.setCarrier_identity(
                //   hyCustomer.getCustomerType().equals("2") ? hyCustomer.getCreditCode() : hyCustomer.getIdcard()
                hyDriver.getIdcard()
        );

        subWayBillDTO.setDriver_identity(
                Collections.singletonList(hyDriver.getIdcard())
        );

        subWayBillDTO.setPlate_number(hyVehicle.getVehicleNumber());
        subWayBillDTO.setSend_time(
                hyShippingNote.getStatusDtLoading() != null ? hyShippingNote.getStatusDtLoading().getTime() : new Date().getTime()
        );
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, 7);// 把日期往后增加7天.整数往后推,负数往前移动
        Date newtime = calendar.getTime();
        subWayBillDTO.setReceive_time(
                hyShippingNote.getStatusDtSign() != null ? hyShippingNote.getStatusDtSign().getTime() : newtime.getTime()
        );
        subWayBillDTO.setLoad_address(hyShippingNote.getSendAddress());
        subWayBillDTO.setLoad_address_latitude(hyShippingNote.getSendLatitude().toString());
        subWayBillDTO.setLoad_address_longitude(hyShippingNote.getSendLongitude().toString());
        subWayBillDTO.setLoad_district(hyShippingNote.getSendAreaCode());

        subWayBillDTO.setReceive_address(hyShippingNote.getReceiveAddress());
        subWayBillDTO.setReceive_address_latitude(hyShippingNote.getReceiveLatitude().toString());
        subWayBillDTO.setReceive_address_longitude(hyShippingNote.getReceiveLongitude().toString());
        subWayBillDTO.setReceive_district(hyShippingNote.getReceiveAreaCode());
        BigDecimal num = new BigDecimal("100");
        int fee = 0;
        if (hyShippingNote.getDriverFee() != null) {
            fee = hyShippingNote.getDriverFee().multiply(num).setScale(0, BigDecimal.ROUND_DOWN).intValue();
        }
        subWayBillDTO.setFreight(fee);
        subWayBillDTO.setInclude_tax("TAX_INCLUDED_AMOUNT");

        List<SubWayBillGoodsDTO> subWayBillGoodsDTOS = getSubWayBillGoodsDTOS(hyShippingNote, hyOrder);
        subWayBillDTO.setSub_way_bill_goods_list(subWayBillGoodsDTOS);

        subWayBillDTO.setTransport_distance(new Double(hyShippingNote.getTransportationDistance()));
        subWayBillDTO.setTravel_distance(new Double(hyShippingNote.getTransportationDistance()));

        subWayBillDTOS.add(subWayBillDTO);
        return subWayBillDTOS;
    }

    /**
     * 快货运-运单-组装货物信息
     *
     * @param hyShippingNote
     * @param hyOrder
     * @return
     */
    private List<SubWayBillGoodsDTO> getSubWayBillGoodsDTOS(HyShippingNote hyShippingNote, HyOrder hyOrder) {
        List<SubWayBillGoodsDTO> subWayBillGoodsDTOS = new ArrayList<>();

        SubWayBillGoodsDTO subWayBillGoodsDTO = new SubWayBillGoodsDTO();
        subWayBillGoodsDTO.setGoods_name(hyShippingNote.getDescriptionOfGoods());

        //        BigDecimal num = new BigDecimal("100");
        //        Integer fee = 0;
        //        if (hyShippingNote.getCostPayTotal() != null) {
        //            fee = hyShippingNote.getCostPayTotal().multiply(num).setScale(0, BigDecimal.ROUND_DOWN).intValue();
        //        }
        //        subWayBillGoodsDTO.setGoods_price(fee);

        String goodClass = hyShippingNote.getCargoTypeClassificationCode();
        GoodsCargoTypeEnum goodsCargoTypeEnum = GoodsCargoTypeEnum.getCargoTypeEnumByVal(goodClass);
        subWayBillGoodsDTO.setGoods_type(goodsCargoTypeEnum.getCargoClass());

        subWayBillGoodsDTO.setGoods_weight(
                hyShippingNote.getGoodsWeightLoading() != null ?
                        hyShippingNote.getGoodsWeightLoading().doubleValue() * 1000 :
                        hyOrder.getTotalGoodsWeight().doubleValue() * 1000
        );

        //        subWayBillGoodsDTO.setGoods_volume(00.0000);
        //        subWayBillGoodsDTO.setTotal_number(1);

        subWayBillGoodsDTOS.add(subWayBillGoodsDTO);
        return subWayBillGoodsDTOS;
    }

    /**
     * 快货运--上传运输协议合同信息
     *
     * @param hyShippingNote
     * @return
     */

    public TosApiBaseResDTO waybillContract(HyShippingNote hyShippingNote) {

        HyShippingNote hyShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (hyShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据!");
        }

        if (!hyShippingNoteDb.getTosIdentification().equals("1")) {
            throw new JeecgBootException("该运单不属于快货运运单!");
        }
        if (hyShippingNoteDb.getShippingStatus().equals("0") || hyShippingNoteDb.getShippingStatus().equals("8")) {
            throw new JeecgBootException("该运单状态无效!");
        }
        HyDriver hyDriver = driverService.getById(hyShippingNoteDb.getDriverId());
        if (hyDriver == null) {
            throw new JeecgBootException("该运单司机信息不存在!");
        }

        HyCompany company = companyService.getById(hyShippingNoteDb.getCompanyId());
        if (company == null) {
            throw new JeecgBootException("该运单分公司信息不存在!");
        }

        String contractPath = tosApiService.uploadFile(hyShippingNote.getShippingContract());

        ContractDTO contractDTO = new ContractDTO();
        contractDTO.setNumber(getNumbers(hyShippingNote.getShippingContract()));
        contractDTO.setWaybill_no(hyShippingNote.getShippingNoteNumber());
        contractDTO.setSub_waybill_no("0000");
        contractDTO.setType("ACTUAL_CONTRACT_CARRIAGE");
        contractDTO.setFirst_class("SINGLE_CONTRACT");
        contractDTO.setExpire_start_time(
                hyShippingNote.getCreateTime().getTime()
        );
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(hyShippingNote.getCreateTime());
        calendar.add(Calendar.DATE, 7);// 把日期往后增加7天.整数往后推,负数往前移动
        Date newtime = calendar.getTime();
        contractDTO.setExpire_end_time(
                newtime.getTime()
        );
        contractDTO.setFile_address(contractPath);

        List<ContractSubjectDTO> contract_subject_list = getContractSubjectDTO(company, hyDriver);
        contractDTO.setContract_subject_list(contract_subject_list);

        contractDTO.setSigning_time(
                hyShippingNote.getCreateTime().getTime()
        );

        return tosApiService.waybillContract(contractDTO);
    }

    /**
     * 合同主体信息
     *
     * @param company
     * @param hyDriver
     * @return
     */
    private List<ContractSubjectDTO> getContractSubjectDTO(HyCompany company, HyDriver hyDriver) {
        List<ContractSubjectDTO> contractSubjectDTOS = new ArrayList<>();
        contractSubjectDTOS.add(
                new ContractSubjectDTO().setSubject_type("PARTY_JIA").setSubject_identity(company.getCreditCode())
        );
        contractSubjectDTOS.add(
                new ContractSubjectDTO().setSubject_type("PARTY_YI").setSubject_identity(hyDriver.getIdcard())
        );
        return contractSubjectDTOS;
    }


    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    private String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    /**
     * 快货运--同步运单轨迹
     *
     * @param hyShippingNote
     * @return
     */

    public TosApiBaseResDTO waybillGeo(HyShippingNote hyShippingNote) {
        HyShippingNote hyShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (hyShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据!");
        }

        if (!hyShippingNoteDb.getTosIdentification().equals("1")) {
            throw new JeecgBootException("该运单不属于快货运运单!");
        }
        if (!hyShippingNoteDb.getShippingStatus().equals("5")) {
            throw new JeecgBootException("该运单未签收!");
        }
        HyVehicle hyVehicle = vehicleService.getById(hyShippingNote.getVehicleId());
        if (hyVehicle == null) {
            throw new JeecgBootException("该运单车辆信息不存在");
        }
        List<GeoPointDTO> tracesInfoDTOS = getGeoPointDTO(hyVehicle, hyShippingNote);
        if (CollectionUtils.isEmpty(tracesInfoDTOS)) {
            throw new JeecgBootException("该运单轨迹信息不存在");
        }

        GeoDTO geoDTO = new GeoDTO();
        geoDTO.setWaybill_no(hyShippingNote.getShippingNoteNumber());
        geoDTO.setSub_waybill_no("0000");
        geoDTO.setDevice_id(hyVehicle.getVehicleNumber());
        geoDTO.setDevice_type("BEIDOU");
        geoDTO.setGeo_point_list(tracesInfoDTOS);
        return tosApiService.waybillGeo(geoDTO);
    }

    /**
     * 快货运--获取运单轨迹
     *
     * @param hyVehicle
     * @param hyShippingNote
     * @return
     */
    private List<GeoPointDTO> getGeoPointDTO(HyVehicle hyVehicle, HyShippingNote hyShippingNote) {
        List<GeoPointDTO> gpsDTOS = new ArrayList<>();
        String startTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtReceive());
        String endTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtUnloading());
        String vehicleColor = StringUtils.isNotEmpty(hyVehicle.getVehiclePlateColorCode()) ? hyVehicle.getVehiclePlateColorCode() : "2";
        WaybillRouteVO waybillRouteVO = waybillRouteService.getWaybillRoute(hyVehicle.getVehicleNumber(), vehicleColor, startTime, endTime, "GCJ02");
        if (waybillRouteVO != null && CollectionUtils.isNotEmpty(waybillRouteVO.getPointDataList())) {
            List<PointDataListVO> pointDataListVOS = waybillRouteVO.getPointDataList();
            int a = pointDataListVOS.size();

            if (a <= 1000) {
                for (PointDataListVO pointDataListVO : pointDataListVOS) {
                    GeoPointDTO gpsDTO = new GeoPointDTO();
                    gpsDTO.setLongitude(pointDataListVO.getLng());
                    gpsDTO.setLatitude(pointDataListVO.getLat());
                    gpsDTO.setGather_time(
                            DateUtils.stringToDateTime(pointDataListVO.getReceiveTime()).getTime());
                    gpsDTOS.add(gpsDTO);
                }
            } else {
                int b = getFrequency(a);
                int n = 1;
                for (PointDataListVO pointDataListVO : pointDataListVOS) {
                    if (n % b == 0) {
                        GeoPointDTO gpsDTO = new GeoPointDTO();
                        gpsDTO.setLongitude(pointDataListVO.getLng());
                        gpsDTO.setLatitude(pointDataListVO.getLat());
                        gpsDTO.setGather_time(
                                DateUtils.stringToDateTime(pointDataListVO.getReceiveTime()).getTime());
                        gpsDTOS.add(gpsDTO);
                    }
                    n++;
                }
            }

        }
        return gpsDTOS;
    }

    /**
     * 快货运-- 上传资金流水
     *
     * @param hyShippingNote
     * @return
     */

    public TosApiBaseResDTO waybillPayment(HyShippingNote hyShippingNote) {
        HyShippingNote hyShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (hyShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据!");
        }

        if (!hyShippingNoteDb.getTosIdentification().equals("1")) {
            throw new JeecgBootException("该运单不属于快货运运单!");
        }
        if (!hyShippingNoteDb.getShippingPayStatus().equals("6")) {
            throw new JeecgBootException("该运单未支付!");
        }
        LambdaQueryWrapper<HyShippingNoteBill> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(HyShippingNoteBill::getShippingId, hyShippingNoteDb.getId());
        HyShippingNoteBill hyShippingNoteBill = hyShippingNoteBillService.getOne(queryWrapper);
        if (hyShippingNoteBill == null) {
            throw new JeecgBootException("该运单支付信息不存在");
        }
        HyDriver hyDriver = driverService.getById(hyShippingNoteDb.getDriverId());
        if (hyDriver == null) {
            throw new JeecgBootException("该运单司机信息不存在!");
        }

        HyCompany company = companyService.getById(hyShippingNoteDb.getCompanyId());
        if (company == null) {
            throw new JeecgBootException("该运单分公司信息不存在!");
        }


        PaymentDTO paymentDTO = new PaymentDTO();
        paymentDTO.setBank_series_no(hyShippingNoteBill.getBillNum());
        paymentDTO.setTo_type("FREIGHT_COMPANY_PAYS_TO_CARRIER");
        paymentDTO.setReport_time(System.currentTimeMillis());

        BigDecimal num = new BigDecimal("100");
        int fee = 0;
        if (hyShippingNote.getDriverFee() != null) {
            fee = hyShippingNote.getDriverFee() .multiply(num).setScale(0, BigDecimal.ROUND_DOWN).intValue();
        }
        paymentDTO.setTotal_amount(fee);
        paymentDTO.setCoin_type("CNY");
        PayeeListDTO payeeListDTO = new PayeeListDTO();
        payeeListDTO.setPayee_name(hyDriver.getDriverName());
        payeeListDTO.setPayee_identity(hyDriver.getIdcard());
        payeeListDTO.setPayee_account(
                hyShippingNoteBill.getCraccno() + hyShippingNoteBill.getCrlogaccno()
        );
        payeeListDTO.setPayee_bank_code(hyShippingNoteBill.getBankCode());

        PaymentDetailDTO paymentDetailDTO = getPaymentDetaiDTO(hyShippingNote, hyShippingNoteBill, company);
        List<PaymentDetailDTO> paymentDetailDTOS = new ArrayList<>();
        paymentDetailDTOS.add(paymentDetailDTO);
        payeeListDTO.setPayment_detail_list(paymentDetailDTOS);

        List<PayeeListDTO> payeeListDTOS = new ArrayList<>();
        payeeListDTOS.add(payeeListDTO);
        paymentDTO.setPayee_list(payeeListDTOS);

        return tosApiService.waybillPayment(paymentDTO);
    }

    /**
     * 快货运--支付流水信息
     *
     * @param hyShippingNote
     * @param hyShippingNoteBill
     * @param company
     * @return
     */
    private PaymentDetailDTO getPaymentDetaiDTO(HyShippingNote hyShippingNote,
            HyShippingNoteBill hyShippingNoteBill,
            HyCompany company) {
        PaymentDetailDTO paymentDetailDTO = new PaymentDetailDTO();
        paymentDetailDTO.setWaybill_no(hyShippingNote.getShippingNoteNumber());
        paymentDetailDTO.setSub_waybill_no("0000");
        paymentDetailDTO.setSeries_no(hyShippingNoteBill.getBillNum());
        BigDecimal num = new BigDecimal("100");
        int fee = 0;
        if (hyShippingNote.getDriverFee() != null) {
            fee = hyShippingNote.getDriverFee().multiply(num).setScale(0, BigDecimal.ROUND_DOWN).intValue();
        }
        paymentDetailDTO.setAmount(fee);
        paymentDetailDTO.setSub_waybill_amount(0);
        paymentDetailDTO.setPay_time(hyShippingNote.getPayDt().getTime());
        paymentDetailDTO.setRemark("支付流水信息");
        paymentDetailDTO.setPay_type("BANK_TRANSFER");
        paymentDetailDTO.setPayer_name(hyShippingNoteBill.getDbaccname());
        paymentDetailDTO.setPayer_identity(company.getCreditCode());
        paymentDetailDTO.setPayer_account(hyShippingNoteBill.getDbaccno());
        paymentDetailDTO.setPayer_bank_code(hyShippingNoteBill.getBankCode());
        return paymentDetailDTO;
    }

    /**
     * 快货运--上传运输节点信息
     *
     * @param hyShippingNote
     * @return
     */
    public TosApiBaseResDTO waybillTransportDetail(HyShippingNote hyShippingNote, String operationType) {
        HyShippingNote hyShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (hyShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据!");
        }
        if (StringUtils.isEmpty(operationType)) {
            throw new JeecgBootException("运单操作类型不能为空!");
        }

        if (!hyShippingNoteDb.getTosIdentification().equals("1")) {
            throw new JeecgBootException("该运单不属于快货运运单!");
        }
        //        HyOrder hyOrder = orderService.getById(hyShippingNoteDb.getOrderId());
        //        if (hyOrder == null) {
        //            throw new JeecgBootException("该运单货源信息不存在!");
        //        }
        HyDriver hyDriver = driverService.getById(hyShippingNoteDb.getDriverId());
        if (hyDriver == null) {
            throw new JeecgBootException("该运单司机信息不存在!");
        }

        TransportDetailDTO transportDetailDTO = new TransportDetailDTO();
        transportDetailDTO.setWaybill_no(hyShippingNoteDb.getShippingNoteNumber());
        transportDetailDTO.setSub_waybill_no("0000");
        transportDetailDTO.setOperation_type(
                operationType.equals("SHIPPING") ? "SHIPPING" : "DISCHARGE"
        );
        transportDetailDTO.setTransport_time(new Date().getTime());
        transportDetailDTO.setLatitude(
                operationType.equals("SHIPPING") ? hyShippingNoteDb.getSendLatitude().toString() : hyShippingNoteDb.getReceiveLatitude().toString()
        );
        transportDetailDTO.setLongitude(
                operationType.equals("SHIPPING") ? hyShippingNoteDb.getSendLongitude().toString() : hyShippingNoteDb.getReceiveLongitude().toString()
        );
        transportDetailDTO.setDriver_identity(hyDriver.getIdcard());

        return tosApiService.waybillTransportDetail(transportDetailDTO);
    }

    /**
     * 快货运--运单补充信息接口
     *
     * @param waybillNo 运单号
     * @param remark
     * @param file_url
     * @return
     */
    public TosApiBaseResDTO waybillSupplement(String waybillNo, String remark, String file_url) {
        if (StringUtils.isEmpty(waybillNo)) {
            throw new JeecgBootException("该运单信息不存在!");
        }
        if (StringUtils.isEmpty(remark)) {
            throw new JeecgBootException("该运单补充信息不存在!");
        }
        if (StringUtils.isEmpty(file_url)) {
            throw new JeecgBootException("该运单补充文件信息不存在!");
        }
        SupplementDTO supplementDTO = new SupplementDTO();
        supplementDTO.setWaybill_no(waybillNo);
        supplementDTO.setRemark(remark);
        String filePath = tosApiService.uploadFile(file_url);
        supplementDTO.setFile_url(filePath);
        return tosApiService.waybillSupplement(supplementDTO);
    }

    /**
     * 快货运--运单确认接口
     *
     * @param waybillNoList 运单号数组
     * @return
     */

    public TosApiBaseResDTO waybillConfirm(List<String> waybillNoList) {
        if (CollectionUtils.isEmpty(waybillNoList)) {
            throw new JeecgBootException("运单号数组不能空!");
        }
        TosApiBaseResDTO tosApiBaseResDTO = tosApiService.waybillConfirm(waybillNoList);

        if (tosApiBaseResDTO.isSuccess() && tosApiBaseResDTO.getData() != null) {
            String res = JSONObject.toJSONString(tosApiBaseResDTO.getData());
            List<WaybillResultResponseBo> waybillResultResponseBos = JSONObject.parseArray(res, WaybillResultResponseBo.class);
            for (WaybillResultResponseBo waybillResultResponseBo : waybillResultResponseBos) {
//                LOGGER.info("HyShippingNoteServiceImpl  waybillConfirm Waybill_no: {} detailRule:{}",
//                        waybillResultResponseBo.getWaybill_no(),
//                        JSONObject.toJSONString(waybillResultResponseBo.getResult_message()));
                if ("ABLE".equals(waybillResultResponseBo.getResult())) {
                    LambdaQueryWrapper<HyShippingNoteBill> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(HyShippingNoteBill::getShippingNoteNumber, waybillResultResponseBo.getWaybill_no());
                    HyShippingNoteBill hyShippingNoteBill = hyShippingNoteBillService.getOne(queryWrapper);
                    hyShippingNoteBill.setTosShippingnoteAble("1");
                    hyShippingNoteBillService.updateById(hyShippingNoteBill);
                }

            }

        }
        return tosApiBaseResDTO;
    }

    /**
     * 快货运--运单自检结果查询接口
     *
     * @param waybillNoList
     * @return
     */

    public TosApiBaseResDTO invoiceWaybillCheck(List<String> waybillNoList) {
        if (CollectionUtils.isEmpty(waybillNoList)) {
            throw new JeecgBootException("运单号数组不能空!");
        }
        TosApiBaseResDTO tosApiBaseResDTO = tosApiService.invoiceWaybillCheck(waybillNoList);

        if (tosApiBaseResDTO.isSuccess() && tosApiBaseResDTO.getData() != null) {
            String res = JSONObject.toJSONString(tosApiBaseResDTO.getData());
            List<WaybillResultResponseBo> waybillResultResponseBos = JSONObject.parseArray(res, WaybillResultResponseBo.class);
            for (WaybillResultResponseBo waybillResultResponseBo : waybillResultResponseBos) {
//                LOGGER.info("HyShippingNoteServiceImpl  waybillConfirm waybill_no: {} result:{} detailRule:{}",
//                        waybillResultResponseBo.getWaybill_no(),
//                        waybillResultResponseBo.getResult(),
//                        JSONObject.toJSONString(waybillResultResponseBo.getFraud_detail_rule_list())
//                );
                if ("ABLE".equals(waybillResultResponseBo.getResult())) {
                    LambdaQueryWrapper<HyShippingNoteBill> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(HyShippingNoteBill::getShippingNoteNumber, waybillResultResponseBo.getWaybill_no());
                    HyShippingNoteBill hyShippingNoteBill = hyShippingNoteBillService.getOne(queryWrapper);
                    hyShippingNoteBill.setTosShippingnoteAble("1");
                    hyShippingNoteBillService.updateById(hyShippingNoteBill);
                }

            }

        }
        return tosApiBaseResDTO;
    }

    /**
     * 快货运--上传托运人合同信息
     *
     * @param hyShippingNote
     * @return
     */

    public TosApiBaseResDTO waybillCustomerContract(HyShippingNote hyShippingNote) {
        HyCustomerCompany customerCompany = customerCompanyService.getByCustomerId(hyShippingNote.getCustomerId());
        if (customerCompany == null) {
            throw new JeecgBootException("该运单托运人与分公司签约信息不存在!");
        }
        HyCustomer customer = customerService.getById(customerCompany.getCustomerId());
        if (customer == null) {
            throw new JeecgBootException("该运单托运人（货主）信息不存在!");
        }

        HyCompany company = companyService.getById(customerCompany.getCompanyId());
        if (company == null) {
            throw new JeecgBootException("该运单分公司信息不存在!");
        }


        ContractDTO contractDTO = new ContractDTO();
        contractDTO.setNumber(getNumbers(customerCompany.getContractNumber()));
        contractDTO.setWaybill_no(hyShippingNote.getShippingNoteNumber());
        //        contractDTO.setSub_waybill_no("0000");
        contractDTO.setType("CONSIGNMENT_CONTRACT");//托运合同(发货人同网络货运签订的合同)
        contractDTO.setFirst_class("SINGLE_CONTRACT");

        //合同期自
        contractDTO.setExpire_start_time(customerCompany.getExpireStartTime().getTime());
        //合同期至
        contractDTO.setExpire_end_time(customerCompany.getExpireEndTime().getTime());

        String contractPath = tosApiService.uploadFile(customerCompany.getImgContract());
        contractDTO.setFile_address(contractPath);


        List<ContractSubjectDTO> contract_subject_list = new ArrayList <>();
        contract_subject_list.add(
                new ContractSubjectDTO().setSubject_type("PARTY_JIA").setSubject_identity(
                        customer.getCustomerType().equals("1") ? customer.getIdcard() : customer.getCreditCode()
                )
        );
        contract_subject_list.add(
                new ContractSubjectDTO().setSubject_type("PARTY_YI").setSubject_identity(company.getCreditCode())
        );

        contractDTO.setContract_subject_list(contract_subject_list);

        contractDTO.setSigning_time(customerCompany.getExpireStartTime().getTime());

        return tosApiService.waybillContract(contractDTO);
    }


    /**
     * 获取频次
     *
     * @param a
     * @return
     */
    private int getFrequency(Integer a) {
        int b = 1;
        if (a > 1000 && a <= 2000) {
            b = 10;
        } else if (a > 2000 && a <= 3000) {
            b = 20;
        } else if (a > 3000 && a <= 4000) {
            b = 30;
        } else if (a > 4000 && a <= 5000) {
            b = 40;
        } else if (a > 5000 && a <= 6000) {
            b = 50;
        } else {
            b = 60;
        }
        return b;
    }

}
